package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.Vector;
import javax.swing.*;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;

import chat.TextChat;
import chat.VoiceChat;

import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

import document.AutoSave;
import document.DocInfo;
import document.DocPermissions;
import document.Document;


import realtime.SendDocumentState;
import rmi.Client;
import rmi.Client_Servant;
import rmi.Server;
import messagepasser.UserInfo;
import messagepasser.ListenSocket;


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * LoggedIn.java
 *
 * Created on Mar 17, 2010, 8:52:59 PM
 */

/**
 *
 * @author keerthy
 */
public class LoggedIn extends javax.swing.JFrame {

	public List<UserInfo> users;
	public List<DocInfo> docs;
	public List<Document> userDocs = new ArrayList <Document>();
	ListenSocket listeningServer;
	public Vector<String> userNames = new Vector<String>();
	public Vector<String> docNames = new Vector<String>();
	Boolean autoSave = true;
	public UserInfo me;
	public Server tecBoxServer;
	TextChat txtchat;
	VoiceChat voiceChat;
	Document chatDoc;
	DocPermissions docPerm;
	//Thread t=new Thread();
	UserInfo destUser=null;

	String destForTextChat;
	String destForVoiceChat;

	public javax.swing.JList getOnlineUsers() {
		return onlineUsers;
	}

	public void setOnlineUsers(javax.swing.JList onlineUsers) {
		this.onlineUsers = onlineUsers;
	}

	/** Creates new form LoggedIn */
	public LoggedIn() {
		//initComponents();
	}

	public LoggedIn(UserInfo user, Server s){
		me = user;
		tecBoxServer = s;

		initComponents();
		//  System.out.println (user.getUsername());	 
		try {
			Client myself = new Client_Servant(this, user.getUserid());
			s.register(myself, user.getUserid());
		} catch (RemoteException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		try {
			docs = s.getDocuments(user.getUserid());
			for (DocInfo d : docs) {
				docNames.add(d.getDocname());
			}
			docList.setListData(docNames);

			listeningServer = new ListenSocket (user.getPort(), userDocs);
			listeningServer.start();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			users = s.getonlineUsers(user.getUserid());
			for (UserInfo u : users) {
				if (u.isOnlinestatus()) {
					userNames.add(u.getUsername());
				}
			}
			onlineUsers.setListData(userNames);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		for (DocInfo d : docs) {
			//	  System.out.println(d.getDocname());
			DocPermissions[] perDocusers;
			try {
				perDocusers = s.getDocUsers(d.getDocid());
				String cont = s.editdoc(d.getDocid());
				if (cont==null)
					cont = "";
				userDocs.add(new Document(d.getDocid(), user, users, perDocusers, d.getDocname(),cont));
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}  
		this.setTitle(me.getUsername());
		//start thread for evrry user

		initPanes (userDocs);  

		if (autoSave == true) {

			Timer t = new Timer();
			AutoSave autoSave = new AutoSave(userDocs, t,s, me.getUserid());
			t.schedule(autoSave, 1000*60, 1000*60);
		}
	}

	public javax.swing.JList getDocList() {
		return docList;
	}

	public void setDocList(javax.swing.JList docList) {
		this.docList = docList;
	}

	public javax.swing.JTabbedPane getjTabbedPane1() {
		return jTabbedPane1;
	}

	public void setjTabbedPane1(javax.swing.JTabbedPane jTabbedPane1) {
		this.jTabbedPane1 = jTabbedPane1;
	}

	public void initPanes(List <Document> userDocs) {

		for (Document d : userDocs) {
			createPage (d);
			this.jTabbedPane1.addTab( d.getDocName(), d.panel );
		}
	}

	public void createPage(Document d)
	{
		d.panel = new JPanel();
		d.contentBox = new JTextArea(d.getContent()+" ");
		d.contentBox.setBorder(new CompoundBorder(
				new LineBorder(Color.GRAY),
				new EmptyBorder(1, 3, 1, 1)));
		d.contentBox.setLineWrap(true);
		d.contentBox.setWrapStyleWord(true);
		d.contentBox.setColumns(40);
		d.contentBox.setRows(29);
		d.contentBox.setMaximumSize(new Dimension(400, 400));
		JScrollPane scrollPane = new JScrollPane(d.contentBox);

		setPreferredSize(new Dimension(450, 110));

		d.panel.add(scrollPane);

		if (d.getAccess().equals("readonly")) {
			d.contentBox.setEditable(false);
		}
	}


	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		jSeparator1 = new javax.swing.JSeparator();
		jPanel1 = new javax.swing.JPanel();
		jScrollPane1 = new javax.swing.JScrollPane();
		docList = new javax.swing.JList();
		jLabel1 = new javax.swing.JLabel();
		jScrollPane2 = new javax.swing.JScrollPane();
		onlineUsers = new javax.swing.JList();
		jLabel2 = new javax.swing.JLabel();
		jPanel3 = new javax.swing.JPanel();
		jScrollPane3 = new javax.swing.JScrollPane();
		jTextArea1 = new javax.swing.JTextArea();
		jTextField1 = new javax.swing.JTextField();
		jTabbedPane1 = new javax.swing.JTabbedPane();
		jPanel2 = new javax.swing.JPanel();
		jScrollPane4 = new javax.swing.JScrollPane();
		jTextArea2 = new javax.swing.JTextArea();
		jMenuBar1 = new javax.swing.JMenuBar();
		jMenu1 = new javax.swing.JMenuItem();
		jMenu2 = new javax.swing.JMenuItem();
		jMenu3 = new javax.swing.JMenuItem();
		jMenu4 = new javax.swing.JMenuItem();
		jMenu5 = new javax.swing.JMenuItem();
		jMenu6 = new javax.swing.JMenuItem();
		exportItem = new javax.swing.JMenuItem();
		popupWindow = new javax.swing.JPopupMenu();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

		jPanel1.setBackground(new java.awt.Color(153, 153, 255));

		docList.setModel(new javax.swing.AbstractListModel() {
			String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
			public int getSize() { return strings.length; }
			public Object getElementAt(int i) { return strings[i]; }
		});
		jScrollPane1.setViewportView(docList);

		jLabel1.setText("Documents");

		onlineUsers.setModel(new javax.swing.AbstractListModel() {
			String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
			public int getSize() { return strings.length; }
			public Object getElementAt(int i) { return strings[i]; }
		});

		onlineUsers.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				onlineUsersMouseClicked(evt);
			}
		});
		jScrollPane2.setViewportView(onlineUsers);

		jLabel2.setText("Users");

		javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
		jPanel1.setLayout(jPanel1Layout);
		jPanel1Layout.setHorizontalGroup(
				jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(jPanel1Layout.createSequentialGroup()
						.addGap(75, 75, 75)
						.addComponent(jLabel2)
						.addContainerGap(93, Short.MAX_VALUE))
						.addGroup(jPanel1Layout.createSequentialGroup()
								.addGap(63, 63, 63)
								.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
								.addContainerGap(66, Short.MAX_VALUE))
								.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)
								.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)
		);
		jPanel1Layout.setVerticalGroup(
				jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(jPanel1Layout.createSequentialGroup()
						.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE))
		);

		jPanel3.setBackground(new java.awt.Color(255, 255, 255));

		jTextArea1.setColumns(20);
		jTextArea1.setRows(5);
		jTextArea1.setText("Chat window");
		jScrollPane3.setViewportView(jTextArea1);

		jTextField1.setText("");
		jTextField1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jTextField1ActionPerformed(evt);
			}
		});

		javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
		jPanel3.setLayout(jPanel3Layout);
		jPanel3Layout.setHorizontalGroup(
				jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
						.addContainerGap()
						.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
								.addComponent(jTextField1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE)
								.addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE))
								.addContainerGap())
		);
		jPanel3Layout.setVerticalGroup(
				jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(jPanel3Layout.createSequentialGroup()
						.addContainerGap()
						.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addContainerGap())
		);

		javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
		jPanel2.setLayout(jPanel2Layout);
		jPanel2Layout.setHorizontalGroup(
				jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGap(0, 0, Short.MAX_VALUE)
		);
		jPanel2Layout.setVerticalGroup(
				jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGap(0, 259, Short.MAX_VALUE)
		);

		jTextArea2.setColumns(20);
		jTextArea2.setRows(5);
		jTextArea2.setText("Advertisements");
		jScrollPane4.setViewportView(jTextArea2);

		jMenu1.setText("Create");
		jMenu1.setSize(1, 1);

		jMenu1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jMenu1ActionPerformed(evt);
			}
		});
		jMenuBar1.add(jMenu1);

		jMenu2.setText("Share");
		jMenu2.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jMenu2ActionPerformed(evt);
			}
		});
		jMenuBar1.add(jMenu2);

		jMenu3.setText("Save");
		jMenu3.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jMenu3ActionPerformed(evt);
			}
		});
		jMenuBar1.add(jMenu3);

		jMenu4.setText("Edit");
		jMenu4.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jMenu4ActionPerformed(evt);
			}
		});
		jMenuBar1.add(jMenu4);

		jMenu5.setText("Invite");
		jMenu5.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jMenu5ActionPerformed(evt);
			}
		});
		jMenuBar1.add(jMenu5);

		jMenu6.setText("Logout");
		jMenu6.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jMenu6ActionPerformed(evt);
			}
		});
		jMenuBar1.add(jMenu6);
		exportItem.setText("Export As PDF");
		exportItem.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				exportItemActionPerformed(evt);
			}
		});
		jMenuBar1.add(exportItem);

		setJMenuBar(jMenuBar1);

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(
				layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
						.addContainerGap()
						.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 465, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
								.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
								.addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE))
								.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
								.addContainerGap())
		);
		layout.setVerticalGroup(
				layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(layout.createSequentialGroup()
						.addContainerGap()
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
								.addGroup(layout.createSequentialGroup()
										.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
												.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
												.addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 259, Short.MAX_VALUE))
												.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
												.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
												.addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 499, Short.MAX_VALUE)
												.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 403, javax.swing.GroupLayout.PREFERRED_SIZE)
												.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
												.addGap(27, 27, 27))
		);

		pack();
	}// </editor-fold>//GEN-END:initComponents
	private void onlineUsersMouseClicked(java.awt.event.MouseEvent evt) {

		if(onlineUsers.getSelectedValue() != null)
		{
			Object[] options = { "TEXT", "VOICE" };
			int choice = JOptionPane.showOptionDialog(null,
					"Text or  Voice choice invite",
					" ",
					JOptionPane.YES_NO_OPTION,
					JOptionPane.QUESTION_MESSAGE,
					null,
					options,
					options[0]);
			String type = null;
			String dest = (String)onlineUsers.getSelectedValue();
			// interpret the user's choice
			if (choice == JOptionPane.YES_OPTION)
			{	
				if(txtchat != null){
					//pop up 
					if(onlineUsers.getSelectedValue() != null)
					{
						Object[] yesNoOptions = { "YES", "NO" };
						int userChoice = JOptionPane.showOptionDialog(null,
								"Do you want to start a new chat?",
								" ",
								JOptionPane.YES_NO_OPTION,
								JOptionPane.QUESTION_MESSAGE,
								null,
								options,
								options[0]);

						if (userChoice == JOptionPane.NO_OPTION)
						{
							//	System.out.println("No new chat ");
							return;
						}

						if (userChoice == JOptionPane.YES_OPTION){
							//	t.stop();
							jTextArea1.setText("");
							//	System.out.println("New chat wanted");
							//tecBoxServer.endChat();
						}
					}
				}
				destForTextChat = dest;
				type = "text";
				//	System.out.println("Text chat yes option" + destForTextChat);
				//Chat doc ended..........................................................................................
			}

			if(choice == JOptionPane.NO_OPTION){
				destForVoiceChat = dest;
				type = "voice";
				if (voiceChat != null) {
					int userChoice = JOptionPane.showOptionDialog(null,
							"Do you want to start a new voice chat?",
							" ",
							JOptionPane.YES_NO_OPTION,
							JOptionPane.QUESTION_MESSAGE,
							null,
							options,
							options[0]);

					if (userChoice == JOptionPane.NO_OPTION)
					{
						//	System.out.println("No new chat ");
						return;
					}

					if (userChoice == JOptionPane.YES_OPTION){
						//	t.stop();
						jTextArea1.setText("");
						//	System.out.println("New chat wanted");
						//tecBoxServer.endChat();
					}	
				}
			}

			try {

				for(UserInfo u : users){
					if(u.getUsername().equals(dest)){
						destUser = u;
						break;
					}
				}
				tecBoxServer.regForChat(me,destUser, type);

			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				System.out.println ("Server/Receiver may be offline");
				//	e.printStackTrace();
			}
		}
	}


	//Added for client req for chat 
	public void startTxtChat(UserInfo dest){

		destForTextChat=dest.getUsername();

		DocPermissions docPerm1=new DocPermissions(1000,me.getUserid(), "readonly");
		DocPermissions docPerm2=new DocPermissions(1000,dest.getUserid(), "readonly");

		DocPermissions[] permArray={docPerm1,docPerm2};
		List<UserInfo> usersText = new ArrayList<UserInfo>();
		usersText.add(dest);

		if (txtchat != null) {
			txtchat.getT().cancel();
			userDocs.remove(chatDoc);

		}
		txtchat = new TextChat(me, this);
		chatDoc = new Document(1000,me,usersText,permArray,"dummy_doc", "");
		userDocs.add(chatDoc);
		txtchat.setDocPasser(chatDoc);

	}
	private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu1ActionPerformed
		//	System.out.println ("Create doc");
		MsgBox message;
		int newDocId = 0;
		String docname = null;
		do{message = new MsgBox
			(new LoggedIn() , "Enter the File Name", true);
		docname = message.getStr();
		}while(message.isOk && (docname==null || docname.length()==0));
		if(docname!=null && docname.length()>0){
			message = new MsgBox
			(new LoggedIn() , "Enter the File Description", true);
			String desc = message.getStr();
			try {
				newDocId = tecBoxServer.createDoc(me.getUserid(), docname, desc);
				if(newDocId==0){
					System.out.println("Document creation failed");
					return;
				}

			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			docNames.add(docname);
			docList.setListData(docNames);
			DocPermissions[] perm = new DocPermissions[1];
			perm[0] = (new DocPermissions(newDocId, me.getUserid(), "owner"));
			String cont = null;
			try {
				cont = tecBoxServer.editdoc(newDocId);
			} catch (RemoteException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			if (cont==null)
				cont = "";
			Document d = new Document(newDocId, me, users, perm, docname,cont);
			createPage (d);
			this.jTabbedPane1.addTab( d.getDocName(), d.panel );

			try {
				docs = tecBoxServer.getDocuments(me.getUserid());
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			userDocs.add(d);
		}
	}

	private void jMenu2ActionPerformed(java.awt.event.ActionEvent evt) {
		// Share Button
		//	System.out.println ("Share doc");
		int i =jTabbedPane1.getSelectedIndex();
		String docname = docNames.get(i);
		int docId = 0;
		DocPermissions[] perm = null;
		//Getting selected tab's doc id
		for(DocInfo d : docs){
			if(d.getDocname().equalsIgnoreCase(docname))
				docId = d.getDocid();
		}
		try {
			perm = tecBoxServer.shareDoc(me.getUserid(), docId);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//System.out.println("DocId = "+docId);
		//for(int j=0;j<perm.length;j++)
		//	System.out.println(perm[j]);
		Object[][] data = new Object[perm.length][2];
		for(int j=0;j<perm.length;j++){
			data[j] = new Object[]{getUserNameFromId(perm[j].getUserid()), perm[j].getPermissions()};
		}
		String permissionTypes[] ={"owner","readonly","edit"};
		String[] columnNames = {"User","Permission"};
		JPanel jpanel = new JPanel();
		JTable table = new JTable(data, columnNames);
		JTextArea username = new JTextArea();
		//JButton shareButton = new JButton("Share");
		JComboBox permissionsList = new JComboBox(permissionTypes);
		jpanel.setLayout(new GridLayout());
		jpanel.add(table);
		jpanel.add(username);
		jpanel.add(permissionsList);
		//jpanel.add(shareButton);

		Object[] OkCancel = { "Add/Edit", "Remove", "Cancel" };
		int a = JOptionPane.showOptionDialog(null, jpanel, "Current Permissions", JOptionPane.DEFAULT_OPTION, JOptionPane.NO_OPTION, null, OkCancel, OkCancel[0]);
		//	System.out.println(a);
		String newUser = null;
		if(a==0){
			newUser=username.getText();
			//	System.out.println("user = "+newUser+" selected item = "+ (String) permissionsList.getSelectedItem()+" docid = "+docId);
			int id = getUserIdFromName(newUser);
			if(id!=0){
				try {
					tecBoxServer.insertPermission(docId, id, (String) permissionsList.getSelectedItem(),me.getUserid());
				} catch (RemoteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		if(a==1){
			newUser=username.getText();
			//	System.out.println("user = "+newUser+" selected item = "+ (String) permissionsList.getSelectedItem()+" docid = "+docId);
			int id = getUserIdFromName(newUser);
			if(id!=0){
				try {
					tecBoxServer.removePermission(docId, id);
				} catch (RemoteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}


	//Helper function to populate the table for share functionality
	public String getUserNameFromId(int id){

		for(int i =0; i < users.size();i++) {
			if(users.get(i).getUserid()== id) {
				return users.get(i).getUsername();
			}
		}

		if(me.getUserid() == id) {
			return me.getUsername();
		}
		return null;
	}

	public Document getDocumentFromId(int id){

		for(int i =0; i < userDocs.size();i++) {
			if(userDocs.get(i).getDocId() == id) {
				return userDocs.get(i);
			}
		}
		return null;
	}

	//Helper Function to get user id from username
	public int getUserIdFromName(String name){

		for(int i =0; i < users.size();i++) {
			if(users.get(i).getUsername().equals(name)) {
				return users.get(i).getUserid();
			}
		}
		if(me.getUsername().equals(name)) {
			return me.getUserid();
		}
		return 0;
	}

	private void jMenu3ActionPerformed(java.awt.event.ActionEvent evt) {
		// Save button

		int i = jTabbedPane1.getSelectedIndex();
		int docId = 0;
		//Getting selected tab's doc id
		for(DocInfo d : docs){
			if(d.getDocname().equalsIgnoreCase(docNames.get(i)))
				docId = d.getDocid();
		}
		// Getting selected tab's page contents
		//	System.out.println("Index = "+jTabbedPane1.getSelectedIndex());
		//contents = userDocs.get(0).getContent();
		//System.out.println("Contents = " + contents);
		//String contents = (jTabbedPane1.getSelectedComponent()).getName();
		String contents = userDocs.get(jTabbedPane1.getSelectedIndex()).getContentBox().getText();
		try {
			tecBoxServer.saveDoc(me.getUserid(), docId, contents);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void jMenu4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu4ActionPerformed
		// TODO add your handling code here:
	}//GEN-LAST:event_jMenu4ActionPerformed

	private void jMenu5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu5ActionPerformed
		// TODO add your handling code here:
	}//GEN-LAST:event_jMenu5ActionPerformed
	private void jMenu6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu5ActionPerformed
		try {
			System.out.println ("logout request");   
			tecBoxServer.logout(me);

			System.exit(1);

			//this.setVisible(false);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}//GEN-LAST:event_jMenu5ActionPerformed

	private void exportItemActionPerformed(java.awt.event.ActionEvent evt) {
		System.out.println("Called");
		JFileChooser fc = new JFileChooser();

		int returnVal = fc.showSaveDialog(this);
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File file = fc.getSelectedFile();
			try{

				int i = jTabbedPane1.getSelectedIndex();
				int docId = 0;
				//Getting selected tab's doc id
				for(DocInfo d : docs){
					if(d.getDocname().equalsIgnoreCase(docNames.get(i)))
						docId = d.getDocid();
				}

				String text= userDocs.get(jTabbedPane1.getSelectedIndex()).getContentBox().getText();

				com.itextpdf.text.Document document = new com.itextpdf.text.Document(PageSize.A4, 36, 72, 108, 180);
				PdfWriter.getInstance(document,new FileOutputStream(file.getAbsolutePath() + ".pdf"));
				document.open();
				document.add(new Paragraph(text));
				System.out.println("Text is inserted into pdf file");
				document.close();
			}catch(Exception e){}
			//This is where a real application would save the file.

		} else {

		}


		// TODO add your handling code here:
	}
	private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {

		//	System.out.println("In jTextFieldActionP ");
		String getText = jTextField1.getText();
		String tokens[] = me.getUsername().split("@");
		jTextArea1.append("\n" + tokens[0] + ":" + getText);
		jTextField1.setText("");

		txtchat.sendChatMsg(destForTextChat,getText);
	}//GEN-LAST:event_jTextField1ActionPerformed
	/**
	 * @param args the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new LoggedIn().setVisible(true);
			}
		});
	}

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JList docList;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JMenuItem jMenu1;
	private javax.swing.JMenuItem jMenu2;
	private javax.swing.JMenuItem jMenu3;
	private javax.swing.JMenuItem jMenu4;
	private javax.swing.JMenuItem jMenu5;
	private javax.swing.JMenuItem jMenu6;
	private javax.swing.JMenuBar jMenuBar1;
	private javax.swing.JPanel jPanel1;
	private javax.swing.JPanel jPanel2;
	private javax.swing.JPanel jPanel3;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JScrollPane jScrollPane2;
	private javax.swing.JScrollPane jScrollPane3;
	private javax.swing.JScrollPane jScrollPane4;
	private javax.swing.JSeparator jSeparator1;
	private javax.swing.JTabbedPane jTabbedPane1;
	public javax.swing.JTextArea jTextArea1;
	private javax.swing.JTextArea jTextArea2;
	private javax.swing.JTextField jTextField1;
	private javax.swing.JList onlineUsers;
	private JPopupMenu popupWindow;
	private javax.swing.JMenuItem exportItem;

	

	public void startVoiceChatReceiver(UserInfo dest) {
		if (voiceChat != null) {
			voiceChat.stop();
		}
		voiceChat = new VoiceChat(dest.getIpaddr());
		
	}

	public void startVoiceChatTx(UserInfo dest) {
		if (voiceChat != null) {
			voiceChat.startTransmitter();
		}
	}


	// End of variables declaration//GEN-END:variables

}
